package smstpl

import (
	"context"
	"gitee.com/bobo-rs/creative-framework/pkg/sredis"
	"gitee.com/bobo-rs/innovideo-services/consts"
	"gitee.com/bobo-rs/innovideo-services/enums"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/library/tools"
	"gitee.com/bobo-rs/innovideo-services/maps"
	"github.com/gogf/gf/v2/errors/gerror"
	"time"
)

// GetTemplateByAlias 根据模板变量获取短信模板-发送短信模板内容
func (t *sSmsTpl) GetTemplateByAlias(ctx context.Context, varAlias enums.SmsAlias) (*model.CurrTemplateItem, error) {
	var (
		item      = &model.CurrTemplateItem{}
		cacheKey  = tools.CacheKey(consts.SmsTemplateVarAlias, string(varAlias))
		cacheFunc = func(ctx context.Context) (interface{}, error) {
			// 获取当前SMS服务模板信息
			return t.CurrTemplateByAlias(ctx, varAlias)
		}
	)

	// 获取缓存数据
	r, err := sredis.NewCache().GetOrSetFunc(ctx, cacheKey, cacheFunc, time.Hour)
	if err != nil {
		return nil, err
	}

	// 转换类型
	if err = r.Struct(&item); err != nil {
		return nil, gerror.Wrapf(err, `读取模板内容转换CurrTemplateItem报错%s`, err.Error())
	}
	return item, nil
}

// RemoveVarAlias 根据SMS变量删除SMS模板数据
func (t *sSmsTpl) RemoveVarAlias(ctx context.Context) {
	cache := sredis.NewCache()
	for key, _ := range maps.SmsTemplateVarAlias {
		_, _ = cache.Remove(ctx, tools.CacheKey(consts.SmsTemplateVarAlias, string(key)))
	}
}
